package com.site.wisdom_construction.controller.iotModule;

import com.site.wisdom_construction.entity.iotModule.RealTimePerson;
import com.site.wisdom_construction.entity.personnelModule.ContractWorkers;
import com.site.wisdom_construction.entity.personnelModule.ManagerialStaff;
import com.site.wisdom_construction.entity.personnelModule.SafetyTraining;
import com.site.wisdom_construction.responseEntity.CompleteInformationResult;
import com.site.wisdom_construction.responseEntity.OneDataResult;
import com.site.wisdom_construction.responseEntity.Page;
import com.site.wisdom_construction.responseEntity.SafetyTrainingResult;
import com.site.wisdom_construction.service.integralSupermarketModule.ConversionRecordService;
import com.site.wisdom_construction.service.iotModule.RealTimePersonService;
import com.site.wisdom_construction.service.personnelModule.*;
import com.site.wisdom_construction.statisticsResult.RealTimePersonCount;
import com.site.wisdom_construction.util.HttpRequest;
import com.site.wisdom_construction.util.TimeUtils;
import com.site.wisdom_construction.util.verification.NoToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import com.site.wisdom_construction.util.imgUtil.Base64ToOss;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.site.wisdom_construction.util.HttpRequest.send;

/** @Author daiyifei @Date 2022/3/10 @Description */
@Api(tags = "人脸识别闸机数据接口")
@RestController
@RequestMapping("RealTimePerson")
@CrossOrigin
public class RealTimePersonController {
  @Autowired private RealTimePersonService realTimePersonService;

  @Autowired private ContractWorkersService contractWorkersService;

  @Autowired private BadnessWorkersService badnessWorkersService;

  @Autowired private HonorWorkersService honorWorkersService;

  @Autowired private SafetyTrainingWorkersService safetyTrainingWorkersService;

  @Autowired private SafetyTrainingService safetyTrainingService;

  @Autowired private ConversionRecordService conversionRecordService;

  @Autowired
  private ManagerialStaffService managerialStaffService;

  @ApiOperation(value = "增加人脸识别信息", notes = "")
  @PostMapping("/pushData")
  @NoToken
  public void addPersonRecord(@RequestBody JSONObject jsonObject) throws IOException {
//    HttpRequest httpRequest = new HttpRequest();
//    String url = "https://jgpt.xzdtjt.com:8443/api/external/monitor-data";
//    JSONObject jsonObjectC = new JSONObject();
//    Date date = new Date();
//    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//    jsonObjectC.put("device_id","70d8deaa-dbc4-4a72-a148-03bc24ea768c");
//    jsonObjectC.put("timestamp", TimeUtils.dateToStampH(dateFormat.format(date)));
//    jsonObjectC.put("values",jsonObject.get("list"));
//    System.out.println("jsonObjectC:"+jsonObjectC);
//    JSONObject jsonObjectR = new JSONObject();
//    jsonObjectR = httpRequest.PushData(url,jsonObjectC);
//    System.out.println("jsonObjectR:"+jsonObjectR);
    String url = "https://jgpt.xzdtjt.com:8443/api/external/monitor-data";
    JSONObject jsonParam = new JSONObject();
    Date date = new Date();
    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm");
    jsonParam.put("device_id","70d8deaa-dbc4-4a72-a148-03bc24ea768c");
    jsonParam.put("timestamp", TimeUtils.dateToStampH(dateFormat.format(date)));
    jsonParam.put("values", jsonObject.get("list"));
    System.out.println("jsonParam:"+jsonParam);
    try {
      String data = send(url,jsonParam,"UTF-8");
      JSONObject jsonObjectc = JSONObject.parseObject(data);
      System.out.println("result="+data);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }


  @ApiOperation(value = "增加人脸识别信息", notes = "")
  @PostMapping("/addPersonRecordZJSDJ")
  @NoToken
  public void addPersonRecord(@RequestBody Map<String, Object> map) throws IOException {
    // map转JSONObject
    JSONObject jsonObject = new JSONObject(map);
    // 获取其中的data
    JSONObject jsonObjectData = jsonObject.getJSONObject("Data");
    // base64转图片上传oss
    String header = "data:image/jpg;base64,";
    String base64 = header + jsonObjectData.getString("PassImageBase64");
    // base64上传oss工具类
    Base64ToOss base64ToOSS = new Base64ToOss();
    String Host = "ZJDQJ/rlsbsj";
    // 传参map
    Map mapR = new HashMap();
    mapR.put("gid", jsonObjectData.get("Gid"));
    // 大桥局标段id
    mapR.put("projectId", 2);
    mapR.put("userName", jsonObjectData.get("UserName"));
    mapR.put("userTypeStr", jsonObjectData.get("UserTypeStr"));
    mapR.put("unitName", jsonObjectData.get("UnitName"));
    mapR.put("positionName", jsonObjectData.get("PositionName"));
    mapR.put("passTime", jsonObjectData.get("PassTime"));
    mapR.put("passResultMsg", jsonObjectData.get("PassResultMsg"));
    mapR.put("inTypeStr", jsonObjectData.get("InTypeStr"));
    mapR.put("doorName", jsonObjectData.get("DoorName"));
    mapR.put("doorIP", jsonObjectData.get("DoorIP"));
    mapR.put("idCardSN", jsonObjectData.get("IDCardSN"));

    // 上传数据
    RealTimePerson realTimePerson = realTimePersonService.findRealTimePersonByGid(mapR);
    if (realTimePerson == null) {
      // 返回oss图片路劲地址
      String imgUrl = base64ToOSS.GenerateImage(base64, Host);
      mapR.put("passImageBase64", imgUrl);
      realTimePersonService.insertRealTimePerson(mapR);
    } else {
      //            System.out.println("通行记录已存在");
    }
  }

  @ApiOperation(value = "增加人脸识别信息", notes = "")
  @PostMapping("/addPersonRecord")
  @NoToken
  public void addPersonRecordZJSDJ(@RequestBody Map<String, Object> map) throws IOException {
    // map转JSONObject
    JSONObject jsonObject = new JSONObject(map);
    // 获取其中的data
    JSONObject jsonObjectData = jsonObject.getJSONObject("Data");
    // base64转图片上传oss
    String header = "data:image/jpg;base64,";
    String base64 = header + jsonObjectData.getString("PassImageBase64");
    // base64上传oss工具类
    Base64ToOss base64ToOSS = new Base64ToOss();
    String Host = "ZJDQJ/rlsbsj";
    // 传参map
    Map mapR = new HashMap();
    mapR.put("gid", jsonObjectData.get("Gid"));
    // 大桥局标段id
    mapR.put("projectId", 1);
    mapR.put("userName", jsonObjectData.get("UserName"));
    mapR.put("userTypeStr", jsonObjectData.get("UserTypeStr"));
    mapR.put("unitName", jsonObjectData.get("UnitName"));
    mapR.put("positionName", jsonObjectData.get("PositionName"));
    mapR.put("passTime", jsonObjectData.get("PassTime"));
    mapR.put("passResultMsg", jsonObjectData.get("PassResultMsg"));
    mapR.put("inTypeStr", jsonObjectData.get("InTypeStr"));
    mapR.put("doorName", jsonObjectData.get("DoorName"));
    mapR.put("doorIP", jsonObjectData.get("DoorIP"));
    mapR.put("idCardSN", jsonObjectData.get("IDCardSN"));

    HttpRequest httpRequest = new HttpRequest();
    String url = "https://jgpt.xzdtjt.com:8443/api/external/worker-shifts";
    JSONObject jsonObjectC = new JSONObject();
    jsonObjectC.put("section_id",6);
    jsonObjectC.put("segment_id",18);

    if (mapR.get("userName").equals("门卫盛")){

    }else {
      // 上传数据
      RealTimePerson realTimePerson = realTimePersonService.findRealTimePersonByGid(mapR);
      if (realTimePerson == null) {
        // 返回oss图片路劲地址
        String imgUrl = base64ToOSS.GenerateImage(base64, Host);
        mapR.put("passImageBase64", imgUrl);
        realTimePersonService.insertRealTimePerson(mapR);

        //数据上传建管平台
        Map mapC = new HashMap();
        mapC.put("projectId",1);
        mapC.put("managerialName",jsonObjectData.get("UserName"));
        mapC.put("workerName",jsonObjectData.get("UserName"));
        String types = (String) jsonObjectData.get("InTypeStr");
        String time = (String) jsonObjectData.get("PassTime");
        int ss = 0;
        if (types.equals("出口")){
          ss = 1;
        }
        ManagerialStaff managerialStaff = managerialStaffService.findManagerialStaffByManagerialName(mapC);
        ContractWorkers contractWorkers = contractWorkersService.findContractWorkersByWorkerName(mapC);
        if (managerialStaff == null){
          if (contractWorkers == null){

          }else {
            jsonObjectC.put("id",contractWorkers.getWorkerCard());
            jsonObjectC.put("timestamp", TimeUtils.dateToStamp(time));
            jsonObjectC.put("type",ss);
            httpRequest.PushData(url,jsonObjectC);

          }
        }else {
          jsonObjectC.put("id",managerialStaff.getManagerialCard());
          jsonObjectC.put("timestamp", TimeUtils.dateToStamp(time));
          jsonObjectC.put("type",ss);
          httpRequest.PushData(url,jsonObjectC);

        }

      } else {
        //            System.out.println("通行记录已存在");
      }
    }
  }

  @ApiOperation(value = "查询全部道闸通行数据", notes = "")
  @PostMapping("/findRealTimePersonByAll")
  public OneDataResult findRealTimePersonByAll(@RequestBody Map map) {
    OneDataResult oneDataResult = new OneDataResult();
    oneDataResult.setData(realTimePersonService.findRealTimePersonByAll(map));
    return oneDataResult;
  }

  @ApiOperation(value = "查询最近四条通行数据", notes = "")
  @PostMapping("/findRealTimePersonByThree")
  public OneDataResult findRealTimePersonByThree(@RequestBody Map map) {
    OneDataResult oneDataResult = new OneDataResult();
    oneDataResult.setData(realTimePersonService.findRealTimePersonByThree(map));
    return oneDataResult;
  }

  @ApiOperation(value = "最近一条数据", notes = "")
  @PostMapping("/findRealTimePersonByNew")
  public OneDataResult findRealTimePersonByNew(@RequestBody Map map) {
    OneDataResult oneDataResult = new OneDataResult();
    oneDataResult.setData(realTimePersonService.findRealTimePersonByNew(map));
    return oneDataResult;
  }

  @ApiOperation(value = "统计实时数据", notes = "")
  @PostMapping("/countRealTimePerson")
  public OneDataResult countRealTimePerson(@RequestBody Map map) {
    OneDataResult oneDataResult = new OneDataResult();
    RealTimePersonCount realTimePersonCount = new RealTimePersonCount();
    realTimePersonCount.setCourseCount(realTimePersonService.countRealTimePersonR(map));
    realTimePersonCount.setPresentCount(
        realTimePersonService.countRealTimePersonR(map)
            - realTimePersonService.countRealTimePersonC(map));
    realTimePersonCount.setDepartureCount(realTimePersonService.countRealTimePersonC(map));
    oneDataResult.setData(realTimePersonCount);
    return oneDataResult;
  }

  @ApiOperation(value = "删除重复数据", notes = "")
  @PostMapping("/findRealTimePersonByNow")
  public void findRealTimePersonByNow(@RequestBody Map map) throws ParseException {
    SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    List<RealTimePerson> realTimePersonList = realTimePersonService.findRealTimePersonByNow();
    for (int i = 0; i <= realTimePersonList.size() - 2; i++) {

      String timeQ = realTimePersonList.get(i).getPassTime();
      String timeH = realTimePersonList.get(i + 1).getPassTime();
      String nameQ = realTimePersonList.get(i).getUserName();
      String nameH = realTimePersonList.get(i + 1).getUserName();
      String inTypeStrQ = realTimePersonList.get(i).getInTypeStr();
      String inTypeStrH = realTimePersonList.get(i + 1).getInTypeStr();
      Date begin = dfs.parse(timeQ);
      Date end = dfs.parse(timeH);
      long between = (end.getTime() - begin.getTime()) / 1000;
      if (nameQ.equals(nameH) && inTypeStrQ.equals(inTypeStrH) && between < 30) {
        realTimePersonService.deleteRealTimePerson(realTimePersonList.get(i).getId());
      }
    }
  }

  @ApiOperation(value = "查询所有信息", notes = "")
  @PostMapping("/findWorkersMessageAll")
  public CompleteInformationResult findWorkersAll(@RequestBody Map map) {
    CompleteInformationResult completeInformationResult = new CompleteInformationResult();
    ContractWorkers contractWorkers = contractWorkersService.findContractWorkersByIdCardSN(map);
    map.put("workersId", contractWorkers.getId());
    // 基本信息
    completeInformationResult.setBasicInformationData(contractWorkers);
    // 不良资信
    completeInformationResult.setBadnessCreditInformationData(
        badnessWorkersService.findBadnessWorkersByIdCardSN(map));
    // 荣誉信息
    completeInformationResult.setHonorCreditInformationData(
        honorWorkersService.findHonorWorkersByIdCardSN(map));
    // 培训信息
    List<Integer> integerList = safetyTrainingWorkersService.findSafetyTrainingByWorkersId(map);
    if (integerList.size() > 0) {
      List<SafetyTrainingResult> safetyTrainingResultList = new ArrayList<>();
      Map mapR = new HashMap();
      for (int i = 0; i < integerList.size(); i++) {
        mapR.put("id", integerList.get(i));
        SafetyTrainingResult safetyTrainingResult =
            safetyTrainingService.findSafetyTrainingById(mapR);
        safetyTrainingResultList.add(safetyTrainingResult);
      }
      completeInformationResult.setTrainInformationData(safetyTrainingResultList);
    }
    // 兑换信息
    completeInformationResult.setConversionInformationData(
        conversionRecordService.findConversionRecordByWorkersId(map));
    return completeInformationResult;
  }

  @ApiOperation(value = "分页模糊查询通行记录", notes = "测试数据:")
  @PostMapping("/findRealTimePersonByPage")
  public Page findHighSupportsRecordByPage(@RequestBody Map map) {
    Page page = new Page();
    page.setPageNo((Integer) map.get("pageNo"));
    page.setPageSize((Integer) map.get("pageSize"));
    page.setTotal(realTimePersonService.Total(map));
    page.setItems(realTimePersonService.findRealTimePersonByPage(map));
    return page;
  }


}
